<?php


namespace App\Jobs\QiPao\Gift;

use App\Enums\RedisKeyEnum;
use App\Enums\RoomEnum;
use App\Jobs\Job;
use App\Models\MainDB\BlindDate\DatingSceneConfig;
use App\Models\MainDB\BlindDate\DatingHeadPictureConfig;
use App\Models\MainDB\BlindDate\DatingUser;
use App\Services\Tools\IdempotentConsume;
use App\Services\Tools\RedisService;
use Illuminate\Support\Facades\Log;

class GiftDatingJob extends Job
{
    // 是否 相亲房  是否进行 判断是否在进行中 是的进行累加 用户 的数据库  带整改
    // 累加到一个 数值  进行 更新 redis的头像框  结束删除掉
    // 是放到一个队列了还是这么滴 ，放队列吧
    protected $data;    //通过give_gift表的id取出来的送礼记录
    const jobName = 'GiftDatingJob';

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function handle()
    {
        if (env('APP_ENV') != 'production') {
            Log::error('GiftDatingJob:' . json_encode(['time' => getMillisecond(), 'data' => $this->data]));
//            {"time":1719546330601,"data":{"id":49737,"user_id":4156,"gift_id":168,"number":1,"gift_user":3451,"room_id":276,
//                "pit_number":2,"add_time":1719546326,"total_price":"520000.00","type":5,"coin":"0.00","room_demand_id":0}
        }
        $idempotentConsumeServer = new IdempotentConsume();
        $data = $this->data;
        $uk = $data['id'] ?? '';
        try {
            // 在后台 存一个list 修改一个进行 添加 取消进行移除  进行匹配
            // 查询 是否为相亲房 是的进来不是进退出
//            $roomType = RedisService::getDatingRoomList($data['room_id']);
//            $roomType = $sys_type_id = app('model_user_room')->getRoomSystemTypeId($data['room_id']);
            $dating_id = RedisService::getDating($data['room_id']);
            if ($idempotentConsumeServer->checkIdempotentRedisKey(self::jobName, $uk) && $dating_id != 0) {
                // 当前房间的key 去查找是否在相亲中 是的 就进行  ，获取 流水线id
                try {
                    $dating_info = DatingUser::query()
                        ->where('dating_id', $dating_id)
                        ->where('room_id', $data['room_id'])
                        ->where('user_id', $data['gift_user'])->first();
                    if (empty($dating_info)) {
                        // 进行添加  用户go
                        $model_user = new DatingUser();
                        $model_user->dating_id = $dating_id;
                        $model_user->pit_number = $data['pit_number'];
                        $model_user->user_id = $data['gift_user'];
                        $model_user->add_time = time();
                        $model_user->room_id = $data['room_id'];
                        $model_user->type = DatingUser::TYPE[$data['pit_number']];
                        $model_user->value = $data['total_price'];
                        $model_user->save();
                    } else {
//                        DatingUser::query()->where('dating_id', $dating_id)
//                            ->where('room_id', $data['room_id'])
//                            ->where('user_id', $data['gift_user'])
                        // 判断 是否公布阶段  是的 直接退出  待整改
                        $dating_info->increment('value', $data['total_price']);
                    }
                    //
                    // 存一下用户帽子麦位进行存然后就有序集合
                    // 查询 当前用户是男女  进行 男女
                    $user_sex = app('redis')->hget(sprintf(RedisKeyEnum::USER_INFO, $data['gift_user']), 'sex');
                    // 存用户 所有的 针对用户  [123 => 10000, 234 => 20000]
                    $highest_pit = RedisService::getDatingMemberAvatar($dating_id, $data['room_id'], $user_sex, $data['total_price'], $data['gift_user']) ?? [];
                    //                    $highest_pit = RedisService::getDatingMemberAvatar($dating_id, $data['room_id'], $dating_info['type'], $data['total_price'], $data['pit_number']);
                    // 帽子 单独存  [ 0 => 100000]

//                    print_r( $data['gift_user']);
//                    print_r("下面是最高的\n");
//                    print_r($highest_pit);
                    $highest_pit_one = array_key_first($highest_pit);
                    $highest_pit_value = $highest_pit[$highest_pit_one];

//                    print_r("\n");
//                    print_r($highest_pit_value);
//                    print_r("\n");
                    // 判断是否有帽子 是否 就判断帽子是否变了 变了就信推送
                    $result_avatar = (object)[];
                    if($highest_pit_one == $data['gift_user']){
                        $pit_info = RedisService::getDatingMemberAvatarMax($dating_id, $data['room_id'], $user_sex, $highest_pit_value, $data['gift_user']);
                        if ($pit_info['is_o']) {
                            // 推送
                            $info_data = DatingHeadPictureConfig::query()->where('id', $pit_info['rate'])->first();
                            if (!empty($info_data)) {
                                // 获取用户信息
                                $result_avatar = [
                                    'user_id' => $data['gift_user'],
                                    'sex' => $user_sex,
                                    'pit_number' => $data['pit_number'],
                                    'special' => $user_sex == 1 ? $info_data['male_special'] : $info_data['girl_special'],
                                    'special_name' => $info_data['name'],
                                ];
                            }
                        }
                    }else{
                        RedisService::getDatingMemberAvatarMaxNew($dating_id, $data['room_id'], $user_sex, $data['gift_user']);
                    }

//                    RedisService::getDatingMemberSceneMax($dating_id, $data['room_id']);
//                    print_r($scene_id);
                    $result_scene = '';
//                    if ($scene_id != 0) {
//                        $scene_data = DatingSceneConfig::query()->where('id', $scene_id)->first();
//                        // 查询  进行推送
//                        if (!empty($scene_data)) {
//                            $result_scene = $scene_data['room_picture'];
//                        }
//                    }
                    $result = [
                        'name' => 'room_' . $data['room_id'],
                        'uni_key' => uniqidReal(),
                        'data' => [
                            'msg' => [
                                'hat_list' => [$result_avatar],
                                'scene' => $result_scene
                            ],
                            'type' => 5085,
                            'time' => time()
                        ]

                    ];
                    //{"senderId":"room_10007",
                    //"targetId":"system",
                    //"objectName":"RC:CmdMsg",
                    //"content":"{\"name\":\"room_10007\",\"uni_key\":\"eebf695a62425\",\"data\":{\"msg\":{\"avatar\":{\"user_id\":4811,\"pit_number\":1,\"special\":\"https:\\\/\\\/yoyo-cs.oss-cn-beijing.aliyuncs.com\\\/gift\\\/15e5c6a19c5a86652d282674945fb36527867ea7.mp4\",\"special_name\":\"\\u5e3d\\u5b501\"},\"scene\":{\"special\":\"https:\\\/\\\/biluo-cs.oss-cn-hangzhou.aliyuncs.com\\\/manage_api\\\/508739aad60c10db1a63ed4adabb2edcb6cad49e.png\"}},\"type\":5085,\"time\":1731406817}}"}
//                    Log::error('res:' . 1);
                    $rcService = app('rongcloud');
                    $res = $rcService->roomPush('system', 'room_' . $data['room_id'], $result, 'RC:CmdMsg');
                } catch (\Exception $exception) {
                    $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName, $uk);
                    Log::error('GiftDatingJob:失败' . $exception->getMessage());
                }
            }
        } catch (\Exception $exception) {
            $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName, $uk);
            Log::error('GiftDatingJob:' . $exception->getMessage());
        }

    }


}
